package com.lujianfei.filesend.ui.server.viewmodel

import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.lujianfei.common.DataBindingDifferUtils
import com.lujianfei.common.LogUtils
import com.lujianfei.filesend.ui.search.adapter.SearchDeviceItem
import com.lujianfei.filetransfer.TcpManager
import com.lujianfei.filetransfer.model.CustomModelBase
import kotlinx.coroutines.launch


/**
 * Author: lujianfei
 * Date: 2023/10/16 17:52
 * Description: 搜索设备
 */

class ServerViewModel: ViewModel() {

    val list = ObservableArrayList<SearchDeviceItem>()
    var onItemClickCallback:((SearchDeviceItem)->Unit)?= null
    val onItemClick:((SearchDeviceItem)->Unit)= {
        onItemClickCallback?.invoke(it)
    }

    val inputNumber = ObservableField("")

    fun onMessageReceive(ipaddress: String, message: String) {
        LogUtils.d("ServerViewModel=", "ipaddress:$ipaddress, message:$message")
        viewModelScope.launch {
            list.find { it.ipaddress == ipaddress }?.let {
                it.lastMessage.set(message)
            }
        }
    }

    fun onClientClose(ipaddress: String) {
        viewModelScope.launch {
            list.find { it.ipaddress == ipaddress }?.let {
                list.remove(it)
            }
        }
    }

    fun onClientAccept(ipaddress: String) {
        viewModelScope.launch {
            list.add(SearchDeviceItem(ipaddress = ipaddress, name = ObservableField(ipaddress), lastMessage = ObservableField("")))
        }
    }

    fun onNameAccept(address: String, name: String) {
        viewModelScope.launch {
            list.find { it.ipaddress == address }?.let {
                it.name.set(name)
            }
        }
    }

    fun load() {
        TcpManager.instance.getClientList().map {
            SearchDeviceItem(ipaddress = it.ipaddress, name = ObservableField(it.name), lastMessage = ObservableField(it.content))
        }.let {
            DataBindingDifferUtils.updateList(list, it)
        }
    }
}